package com.stu.ssm_02.controller;

import com.stu.ssm_02.entity.User;
import com.stu.ssm_02.exception.BusinessException;
import com.stu.ssm_02.service.IUserService;
import com.stu.ssm_02.vo.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * ClassName: LoginController
 * Package: com.stu.ssm_02.controller
 * Description: @Version 1.0
 */
@Controller
@RequestMapping("/login")
public class LoginController {
    @Autowired
    private IUserService userService;
    @PostMapping("")
    public String login(User user, Model model, HttpServletRequest request) throws BusinessException {
        List<User> userList=userService.getUserByUsername(user.getUsername());
        if(userList==null||userList.size()==0){
            throw new BusinessException("该用户名不存在");
        }else if(userList.size()==1){
            if(userList.get(0).getPassword().equals(user.getPassword())){
                //登录成功
                HttpSession session = request.getSession();
                session.setAttribute("loginUser",userList.get(0));
                return "redirect:/user/list";
            }else{
                throw new BusinessException("密码错误");
            }
        }else{
            throw new BusinessException("该用户名存在多个");
        }
    }

    @PostMapping("/ajax")
    @ResponseBody
    public AjaxResult<String> login(@RequestBody User user, HttpServletRequest request){
        List<User> userList=userService.getUserByUsername(user.getUsername());
        AjaxResult<String> ajaxResult = new AjaxResult();
        if(userList==null||userList.size()==0){
            ajaxResult.setCode(400);
            ajaxResult.setMsg("用户名不存在");
        }else if(userList.size()==1){
            if(userList.get(0).getPassword().equals(user.getPassword())){
                //登录成功
                HttpSession session = request.getSession();
                session.setAttribute("loginUser",userList.get(0));
                ajaxResult.setMsg("登陆成功");
            }else{
                ajaxResult.setCode(400);
                ajaxResult.setMsg("密码错误");
            }
        }else {
            ajaxResult.setCode(400);
            ajaxResult.setMsg("该用户名存在多个");
        }
        return ajaxResult;
    }


    @RequestMapping("/goToLogin")
    public String goToLogin(){
        return "login";
    }



// 局部异常处理
//    @ExceptionHandler(value = {BusinessException.class})
//    public String handlerException(BusinessException e, HttpServletRequest request) {
//        // 需要手动设置错误信息到页面
//        request.setAttribute("errorStr", e.getMsg());
//        return "error";
//    }
}
